package proxy

import (
	"bufio"
	"flag"
	"fmt"
	"golang.org/x/net/netutil"
	"io"
	"net"
	"net/http"
	"os"
	"strings"
	"sync"
	"time"
	//"golang.org/x/net/http2"
	//"golang.org/x/net/http2/h2c"
)

var lock sync.Mutex
var trueList []string
var ip string
var list string
var wg sync.WaitGroup

func Start() {
	flag.StringVar(&ip, "l", ":9897", "-l=0.0.0.0:9897 指定服务监听的端口")
	flag.StringVar(&list, "d", "127.0.0.1:1789,127.0.0.1:1788", "-d=127.0.0.1:1789,127.0.0.1:1788 指定后端的IP和端口,多个用','隔开")
	flag.Parse()
	trueList = strings.Split(list, ",")
	if len(trueList) <= 0 {
		fmt.Println("后端IP和端口不能空,或者无效")
		os.Exit(1)
	}
	//wg.Add(1)
	go startHttp()
	go startHttp1()
	server()
	//wg.Wait()
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "hello world")
}
func IndexHandler1(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "hello world1")
}

type httpServer struct {
	tag   string
	index int
}

func (this *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	url := r.URL.String()
	fmt.Println("ServeHTTP收到请求"+this.tag, fmt.Sprintf("%v", this.index), url)
	fmt.Fprintln(w, this.tag, fmt.Sprintf("%v", this.index), url)
	this.index++
	if url == "/a" {
		time.Sleep(time.Second * 10)
	}

	fmt.Println("ServeHTTP收到请求结束"+this.tag, fmt.Sprintf("%v", this.index), r.URL.String())

}

func startHttp() {
	fmt.Println("start http...")
	httpServerObj := &httpServer{tag: "a"}
	/*
		//http.HandleFunc("/", IndexHandler)
		err := http.ListenAndServe("127.0.0.1:1789", httpServerObj)
		fmt.Println("err:", err)*/

	l, err := net.Listen("tcp", "127.0.0.1:1789")
	if err != nil {
		fmt.Printf("Listen: %v\n", err)
		return
	}
	defer l.Close()
	l = netutil.LimitListener(l, 1)

	http.Serve(l, httpServerObj)
}

func startHttp1() {
	fmt.Println("start http1...")
	httpServerObj := &httpServer{tag: "b"}
	err := http.ListenAndServe("127.0.0.1:1788", httpServerObj)
	fmt.Println("err1:", err)
}

func server() {
	lis, err := net.Listen("tcp", ip)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer lis.Close()
	for {
		conn, err := lis.Accept()
		if err != nil {
			fmt.Println("建立连接错误:", err)
			continue
		}
		fmt.Println("server：", conn.RemoteAddr(), conn.LocalAddr())
		go handle(conn)
	}
}

//代理实现
func handle(sconn net.Conn) {
	defer sconn.Close()
	ip, ok := getIP()
	fmt.Println("to:ip:", ip)
	if !ok {
		return
	}
	dconn, err := net.Dial("tcp", ip)
	if err != nil {
		fmt.Printf("连接%v失败:%v\n", ip, err)
		return
	}
	ExitChan := make(chan bool, 1)
	//var r []byte
	go func(sconn net.Conn, dconn net.Conn, Exit chan bool) {
		fmt.Println("开始发送:", ip, err)
		//sconn.Read(r)
		//fmt.Println("发送数据", string(r))
		_, err := io.Copy(dconn, sconn)
		fmt.Println("发送数据失败:", ip, err)
		ExitChan <- true
	}(sconn, dconn, ExitChan)
	go func(sconn net.Conn, dconn net.Conn, Exit chan bool) {
		fmt.Println("开始接收:", ip, err)
		//sconn.Read(r)
		//fmt.Println("接收数据", string(r))
		_, err := io.Copy(sconn, dconn)
		fmt.Println("接收数据失败:", ip, err)
		ExitChan <- true
	}(sconn, dconn, ExitChan)
	<-ExitChan
	fmt.Println("关闭")
	dconn.Close()
}

func RunH2Server(l net.Listener) {
	//svr := &HTTPServer{}
	//
	//s2 := &http2.Server{}
	//
	//s1 := http.Server{
	//	TLSConfig: &tls.Config{
	//		InsecureSkipVerify: true,
	//	},
	//	Handler: h2c.NewHandler(svr, s2),
	//}
	//s1.Serve(l)
}

func DownFile() {
	url := "http://wx.qlogo.cn/Vaz7vE1/64"
	resp, err := http.Get(url)
	if err != nil {
		fmt.Fprint(os.Stderr, "get url error", err)
	}

	defer resp.Body.Close()

	out, err := os.Create("/tmp/icon_wx_2.png")
	wt := bufio.NewWriter(out)

	defer out.Close()

	n, err := io.Copy(wt, resp.Body)
	fmt.Println("write", n)
	if err != nil {
		panic(err)
	}
	wt.Flush()
}

func getIP() (string, bool) {
	lock.Lock()
	defer lock.Unlock()
	if len(trueList) < 1 {
		return "", false
	}
	ip := trueList[0]
	trueList = append(trueList[1:], ip)
	return ip, true
}
